package Controllers
{
	import Components.Block;
	import nl.jorisdormans.phantom2D.core.Component;
	import nl.jorisdormans.phantom2D.core.Composite;
	import nl.jorisdormans.phantom2D.core.InputState;
	import nl.jorisdormans.phantom2D.objects.GameObjectComponent;
	import nl.jorisdormans.phantom2D.objects.IInputHandler;
	/**
	 * ...
	 * @author Sebastiaan
	 */
	public class KeyHandler extends GameObjectComponent implements IInputHandler
	{
		
		public static const E_CHANGE_DIRECTION : String = "changeDirection";
		public var reverse :int = 1;
		
		public static var xmlDescription : XML = < KeyHandler acceleration = "Number" />;
		public static var xmlDefault : XML = < KeyHandler acceleration = "1000" /> ;
		
		public static function generateFromXML(xml:XML) : Component 
		{
			var comp : Component = new KeyHandler();
			comp.readXML(xml);
			return comp;
		}
		
		private var acceleration : Number;
		private var lastX : Number;
		private var lastY : Number;
		
		public function KeyHandler(acceleration : Number = 1000) 
		{
			this.acceleration = acceleration;
			lastX = 1;
			lastY = 0;
		}
		
		override public function generateXML():XML 
		{
			var xml : XML = super.generateXML();
			xml.@acceleration = acceleration;
			return super.generateXML();
		}
		
		override public function readXML(xml:XML):void 
		{
			super.readXML(xml);
			if (xml.@acceleration.length() > 0)
				acceleration = xml.@acceleration;
		}
		
		override public function onAdd(composite:Composite):void 
		{
			super.onAdd(composite);
			if (!gameObject.mover)
				throw new Error("KeyHandler requires that his GameObject has a mover component!");
		}
		
		public function handleInput(elapsedTime : Number, currentstate : InputState, previousState : InputState) : void
		{
			var dx : Number = 0;
			var dy : Number = 0;
			
			
			if (currentstate.mouseButton) dy -= 2;
			
			if (dx != 0 && dy != 0)
			{
				dx *= Math.SQRT1_2;
				dy *= Math.SQRT1_2;
			}
			
			elapsedTime *= acceleration;
			gameObject.mover.velocity.x += dx * elapsedTime;
			gameObject.mover.velocity.y += dy * reverse * elapsedTime;
			if ((lastX!=dx || lastY!=dy) && (dx!=0 || dy!=0)) {
				lastX = dx;
				lastY = dy;
				parent.sendMessage(E_CHANGE_DIRECTION, { dx: dx, dy: dy } );
				
			}
		}
		
		override public function handleMessage(message:String, data:Object = null):int 
		{
			switch(message)
			{
				case "Reverse":	
								reverse = -1;
								trace("Reverse");
								break;
					
				
				case "ReverseBack":	
								reverse = 1;
								trace("ReverseBack");
								break;
			}
			return super.handleMessage(message, data);
		}
	}
}